package iii.myangeloldman;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
import packet.updateLocation;
import DataClass.OldClock;
import TCP.Communication.LinkerClient;
import TCP.Communication.Role;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	public static LinkerClient lcl;
	private LocationManager locationManager;
	public static MainActivity oldMain;
	private Criteria criteria;
	private String oldmanID = "old1";
	private Location myLocation;
	Button btnCall = null;
	public static List<OldClock> list;
	GregorianCalendar c1, c2, c3, c4;
	AlarmManager AM1, AM2, AM3, AM4;
	PendingIntent Pi1, Pi2, Pi3, Pi4;
	public static Handler handler = new Handler();
	Notification notifi;

	// thread 執行onCreate
	public void connectSocket() {
		Thread threadCon = new Thread(new Runnable() {
			public void run() {
				try {
					concetion();
					getLocation();

				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		threadCon.start();

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		InitComp();
		connectSocket();
		notifi=null;
		oldMain = this;
		//UpdateTime();
	}

	OnClickListener btnCall_click = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Uri uri = Uri.parse("tel:0928325615"); 
			Intent it = new Intent(Intent.ACTION_CALL, uri); 
			startActivity(it); 
		}
	};

	private void InitComp() {
		btnCall = (Button) findViewById(R.id.btnCall);
		btnCall.setOnClickListener(btnCall_click);

	}

	// 連線
	public void concetion() throws UnknownHostException, IOException {
		lcl = new LinkerClient("54.199.230.253", 7777, Role.admin);
		lcl.setUserName(oldmanID);
	}

	// ���m�e�X
	public void getLocation() {
		// ��oLocationManager����
		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

		// �إ�Criteria�W�h����A�ín�D��Ǫ��w��\��
		criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);

		// �̾�criteria���W�h�^�ǳ̾A�X���w��W�١A
		// true�N��u�^�ǥثe�i���Ѫ��w��W��
		String provider = locationManager.getBestProvider(criteria, true);

		// �Q�Ϋ�w���w��W�٨Ө�o�ۤv�̷s��m
		Location myLocation = locationManager.getLastKnownLocation(provider);

		this.myLocation = myLocation;
		// updateMyLocationInfo(myLocation);
		if (myLocation != null) {
			updateLocation p = new updateLocation();
			p.id = 1;

			p.Latitude = myLocation.getLatitude();
			p.longitude = myLocation.getLongitude();
			lcl.send(p);
		}

	}

	public static Runnable Test() {
		return new Runnable() {
			@Override
			public void run() {
				oldMain.UpdateTime();
			}
		};
	}

	// 更新時間資料
	public void UpdateTime() {
		try {
//			Toast.makeText(MainActivity.this, "SSS", Toast.LENGTH_SHORT).show();
			// got data here

			// for (OldClock o : list) {
			// String s = "";
			// s += o.time;
			// Toast.makeText(MainActivity.this, s, Toast.LENGTH_LONG).show();
			// }

			// write to SP
			int i = 0;
			// for each get oldClock
			 for (OldClock o : list) {
			 SharedPreferences SP = getSharedPreferences("set" + i, 0);
			 Editor e = SP.edit();
			 String result = "";
			 e.putInt("Medid", o.id).commit();
			 e.putString("OnOff", o.onoff).commit();
			
			 e.putString("EatTime", o.time).commit();
			
//			 Toast.makeText(MainActivity.this, SP.getString("EatTime",
//			 "no time")
//			 , Toast.LENGTH_LONG).show();
			
			 if (o.sun.equals("true"))
			 result += "1";
			 if (o.mon.equals("true"))
			 result += "2";
			 if (o.tue.equals("true"))
			 result += "3";
			 if (o.wed.equals("true"))
			 result += "4";
			 if (o.thu.equals("true"))
			 result += "5";
			 if (o.fri.equals("true"))
			 result += "6";
			 if (o.sat.equals("true"))
			 result += "7";
			 e.putString("soundF", o.soundF1).commit();
			 e.putString("picF", o.picF1).commit();
			 e.putString("Date", result).commit();
			 // write pic and sound
			 SaveFile(o.bPic, o.picF1);
			 SaveFile(o.bSound, o.soundF1);
			 i++;
			 }

			// call setAlarm method
			SetAlarm();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 設定鬧鐘
	private void SetAlarm() {
		String state1 = "0", state2 = "0", state3 = "0";
		String Time1 = "", Time2 = "", Time3 = "";
		String result1 = "", result2 = "", result3 = "";
		c1 = new GregorianCalendar();
		c2 = new GregorianCalendar();
		c3 = new GregorianCalendar();
		c4 = new GregorianCalendar();
		// set value above

		// Cancel all Alarm
		if (AM1 != null) {
			AM1.cancel(Pi1);
		}
		if (AM2 != null) {
			AM2.cancel(Pi2);
		}
		if (AM3 != null) {
			AM3.cancel(Pi3);
		}

		//
		SharedPreferences table1 = getSharedPreferences("set" + 0, 0);
		SharedPreferences table2 = getSharedPreferences("set" + 1, 0);
		SharedPreferences table3 = getSharedPreferences("set" + 2, 0);
		String switch1 = table1.getString("OnOff", "0");
		Time1 = table1.getString("EatTime", "no time");
		// Alarm 1
		if (switch1.equals("1")) {// 檢查開關
			String result = table1.getString("Date", "no time");
			Time1 = table1.getString("EatTime", "0");
			int HH = Integer.parseInt(Time1.substring(0, 2));
			int mm = Integer.parseInt(Time1.substring(3, 5));
			c1.set(Calendar.HOUR_OF_DAY, HH);
			c1.set(Calendar.MINUTE, mm);
			c1.set(Calendar.SECOND, 00);
			//c1.set(2014, 2, 12, 15, 29);

			String pattern = "yyyy-MM-dd E kk:mm:ss";
			SimpleDateFormat fm1 = new SimpleDateFormat(pattern);
//			Toast.makeText(MainActivity.this, fm1.format(c1.getTime()),
//					Toast.LENGTH_SHORT).show();

			if (result.contains(String.valueOf(c1.get(Calendar.DAY_OF_WEEK)))) {// 檢查星期
				if (System.currentTimeMillis() < c1.getTimeInMillis()) {// 檢查時間大小
					Intent intent = new Intent();
					intent.setClass(this, MyCall1.class);
					Pi1 = PendingIntent.getBroadcast(MainActivity.this, 1,
							intent, 0);
					AM1 = (AlarmManager) this
							.getSystemService(MainActivity.ALARM_SERVICE);
					AM1.set(AlarmManager.RTC_WAKEUP, c1.getTimeInMillis(), Pi1);
//					Toast.makeText(MainActivity.this, "Alarm Start",
//							Toast.LENGTH_SHORT).show();
				} 
			} 
		}

		// Alarm 2
		String switch2 = table2.getString("OnOff", "0");
		Time2 = table2.getString("EatTime", "no time");
		if (switch2.equals("1")) {//start alarm2
			
			String result = table2.getString("Date", "no time");
			Time2 = table2.getString("EatTime", "0");
			int HH = Integer.parseInt(Time2.substring(0, 2));
			int mm = Integer.parseInt(Time2.substring(3, 5));
			c2.set(Calendar.HOUR_OF_DAY, HH);
			c2.set(Calendar.MINUTE, mm);
			c2.set(Calendar.SECOND, 00);
			//c2.set(2014, 2, 12, 15, 30);

			String pattern = "yyyy-MM-dd E kk:mm:ss";
			SimpleDateFormat fm1 = new SimpleDateFormat(pattern);
//			Toast.makeText(MainActivity.this, fm1.format(c2.getTime()),
//					Toast.LENGTH_SHORT).show();

			if (result.contains(String.valueOf(c2.get(Calendar.DAY_OF_WEEK)))) {// 檢查星期
				if (System.currentTimeMillis() < c2.getTimeInMillis()) {// 檢查時間大小
					Intent intent = new Intent();
					intent.setClass(this, MyCall2.class);
					Pi2 = PendingIntent.getBroadcast(MainActivity.this, 2,
							intent, 0);
					AM2 = (AlarmManager) this
							.getSystemService(MainActivity.ALARM_SERVICE);
					AM2.set(AlarmManager.RTC_WAKEUP, c2.getTimeInMillis(), Pi2);
//					Toast.makeText(MainActivity.this, "Alarm2 Start",
//							Toast.LENGTH_SHORT).show();
				} 
			} 
		} 
		//end alarm2

		// Alarm 3
		String switch3 = table3.getString("OnOff", "0");
		Time3 = table3.getString("EatTime", "no time");
		if (switch3.equals("1")) {//Start Alarm 3
			String result = table3.getString("Date", "no time");
			Time3 = table3.getString("EatTime", "0");
			int HH = Integer.parseInt(Time3.substring(0, 2));
			int mm = Integer.parseInt(Time3.substring(3, 5));
			c3.set(Calendar.HOUR_OF_DAY, HH);
			c3.set(Calendar.MINUTE, mm);
			c3.set(Calendar.SECOND, 00);
			//c3.set(2014, 2, 12, 15, 31);

			String pattern = "yyyy-MM-dd E kk:mm:ss";
			SimpleDateFormat fm1 = new SimpleDateFormat(pattern);
//			Toast.makeText(MainActivity.this, fm1.format(c3.getTime()),
//					Toast.LENGTH_SHORT).show();

			if (result.contains(String.valueOf(c3.get(Calendar.DAY_OF_WEEK)))) {// 檢查星期
				if (System.currentTimeMillis() < c3.getTimeInMillis()) {// 檢查時間大小
					Intent intent = new Intent();
					intent.setClass(this, MyCall3.class);
					Pi3 = PendingIntent.getBroadcast(MainActivity.this, 3,
							intent, 0);
					AM3 = (AlarmManager) this
							.getSystemService(MainActivity.ALARM_SERVICE);
					AM3.set(AlarmManager.RTC_WAKEUP, c3.getTimeInMillis(), Pi3);
//					Toast.makeText(MainActivity.this, "Alarm3  Start",
//							Toast.LENGTH_SHORT).show();
				} 
			}
		} 
		//end alarm3

		// Alarm 4
		//Notification
		
		Intent noti = new Intent();
		noti.setClass(MainActivity.this, MainActivity.class);
		Pi4 = PendingIntent.getBroadcast(MainActivity.this, 4,
				noti, 0);
		NotificationManager notificationManager 
	      = (NotificationManager)getSystemService(
	        MainActivity.NOTIFICATION_SERVICE);
		
		
		notifi=new Notification.Builder(MainActivity.this)
							.setContentTitle("My Angel 通知")
							.setContentText("鬧鐘時間已更新")
							.setContentIntent(Pi4)
							.setDefaults(Notification.DEFAULT_ALL)
							.setSmallIcon(R.drawable.angel)
							.build();
		notificationManager.notify(0, notifi);
		
		//Notification end
							
	}

	public void SaveFile(LinkedList<byte[]> bList, String name) {
		FileOutputStream fos = null;
		try {
			String path = "";
			File imageDir = Environment
					.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
			path = new File(imageDir, name).toString();
			fos = new FileOutputStream(path);
			for (byte[] bb : bList) {
				fos.write(bb);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fos.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
